<?php

namespace App\Services;


use Config;
use Mockery\Exception;

class Sms {


    /**
     * 服务器地址
     * @var string
     */
    protected $host = 'http://itfc.heyanzheng.com/sms/send.do';

    /**
     * 用户ID
     * @var string
     */
    protected $userId = '242';

    /**
     * 秘钥
     * @var string
     */
    protected $secrect = 'nTcNl0';
    /**
     * 接口请求方式
     * @var string
     */
    protected $httpMethod = 'POST';

    /**
     * 字符编码
     * @var string
     */
    protected $charSet = 'UTF-8';

    /**
     * 请求参数标识
     * @var string
     */
    protected $reqName = 'req';

    /**
     * 参数数组
     * @var array
     */
    protected $params = [];


    /** 设置参数
     * @param $key
     * @param $value
     */
    public function setParam($key,$value){
        $this->params[$key] = $value;
    }

    public function sendMsg($templateId,$smsSignId,$phone,$content,$smsId=''){

        $this->setParam('templateId',strval($templateId));
        $this->setParam('smsSignId',strval($smsSignId));
        $this->setParam('phone',strval($phone));
        $this->setParam('content',$content);
        $this->setParam('smsId',strval($smsId));
        $signedParam = $this->signParam();

        return $this->makeRequest($signedParam);

    }

    /**
     * 发送注册短信
     * @param $phone
     * @param $code
     * @return mixed|string
     */
    public function regMsg($phone,$code){

        return $this->sendMsg('fix2','181',$phone,'尊敬的用户，您的验证码是：'.$code.'，阿福易购欢迎您的注册。');

    }

    /**
     * 参数签名
     * @param $param
     */
    private function signParam(){

        $params = $this->params;

        //1. 生成json data={"templateId":"12","smsSignId":"23","phone":"13311197067","content":"测试全流程短信","smsId":""}

        $paramJson = json_encode($params,JSON_UNESCAPED_UNICODE);

        //2. json 升序排列  sdata="""""""""""""""""""",,,,011111223336779:::::IIISacdddeeeeghilmmmnnnnooppsssstttt{}  信全流测短程试

        $orderParam = $this->bubbleSort($paramJson);

        //3. 将接入秘钥 busCode 放到排序后的字符串头进行 md5 加密(32 位),再转成小写

         $sign = strtolower(md5($this->secrect.$orderParam));

        //4. 拼成最终的请求串,

        $content = [
            'post'=>[
                'sign'=>$sign,
                'userid'=>strval($this->userId)
            ],
            'data'=>$params
        ];


        $data[$this->reqName] = base64_encode(json_encode($content,JSON_UNESCAPED_UNICODE));


        return $data;

    }




    private function makeRequest($data){

        $param = http_build_query($data);



        try {
            $ch = curl_init ();
            curl_setopt ( $ch, CURLOPT_URL,$this->host.'?'.$param);
            curl_setopt ( $ch, CURLOPT_POST, 1 );
            curl_setopt ( $ch, CURLOPT_HEADER, 0 );
            curl_setopt ( $ch, CURLOPT_POSTFIELDS, []);
            curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
            $return = curl_exec ( $ch );
            curl_close ( $ch);
            if (json_decode($return)){
                return json_decode($return);
            }else{
                return json_encode(['code'=>'500','服务器返回解析错误'],JSON_UNESCAPED_UNICODE);
            }

        }catch (Exception $e){

            return json_encode(['code'=>'500','客户端请求失败:'.$e->getMessage(),JSON_UNESCAPED_UNICODE]);

        }

    }

    private function bubbleSort($str)
    {
        if ($str!=''){
            $arr = $this->mbStringToArray($str);
        }else{
            return [];
        }

        $len=count($arr);
        //该层循环控制 需要冒泡的轮数
        for($i=1;$i<$len;$i++)
        { //该层循环用来控制每轮 冒出一个数 需要比较的次数
            for($k=0;$k<$len-$i;$k++)
            {
                if($arr[$k]>$arr[$k+1])
                {
                    $tmp=$arr[$k+1];
                    $arr[$k+1]=$arr[$k];
                    $arr[$k]=$tmp;
                }
            }
        }
        return implode($arr);
    }

    /**
     * 转编码
     * @param $string
     * @return array
     */
    private function mbStringToArray ($string) {
        $strlen = mb_strlen($string);
        while ($strlen) {
            $array[] = mb_substr($string,0,1,"UTF-8");
            $string = mb_substr($string,1,$strlen,"UTF-8");
            $strlen = mb_strlen($string);
        }
        return $array;
    }




}